﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using RGBFinder.Resources;
using System.Threading;
using Microsoft.Phone.Shell;

namespace RGBFinder
{
    public partial class NewGamePage : PhoneApplicationPage
    {
        Random rnd = new Random();
        Timer timer;
        SetType current_type = SetType.None;
        GameStatus status;
        public static GameDifficulty difficulty = GameDifficulty.Normal;
        public static bool start_new_game = false;

        public NewGamePage()
        {
            InitializeComponent();
            if (timer != null)
            {
                timer.Dispose();
            }
            timer = new Timer(new TimerCallback(Timer_Callback), null, 0, 1000);

            ApplicationBarIconButton newgame = new ApplicationBarIconButton() { Text = Strings.NewGame, IsEnabled = true };
            if (App.CurrentTheme == App.Theme.Dark)
            {

                newgame.IconUri = new Uri("\\Images\\dark\\appbar.add.rest.png", UriKind.Relative);
            }
            else
            {

                newgame.IconUri = new Uri("\\Images\\light\\appbar.add.rest.png", UriKind.Relative);
            }

            newgame.Click += NewGame_Button_Click;

            ApplicationBar.Buttons.Add(newgame);
            status = new GameStatus();

        }

        private void NewGame_Button_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(Strings.AreYouSureToExit, "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                status = null;
                NavigationService.GoBack();
            }
        }
        private void Timer_Callback(object o)
        {
            Dispatcher.BeginInvoke(() => UpdateTimer());
        }
        private void UpdateTimer()
        {
            Timer_Area.Text = Strings.Timer + status.timer.ToString();
            if (!status.enableTimer)
                return;
            status.timer += new TimeSpan(0, 0, 1);
            Timer_Area.Text = Strings.Timer + status.timer.ToString();
        }

        public void NewGame()
        {
            DisableSlider();
            start_new_game = false;
            if (status == null)
                status = new GameStatus();
            status.secret_color = Color.FromArgb(255, (byte)(rnd.Next(0, 1000) % 256), (byte)(rnd.Next(0, 1000) % 256), (byte)(rnd.Next(0, 1000) % 256));
            status.difficulty = difficulty;
            status.enableTimer = false;
            status.timeSpan_Ticks = 0;
            do
            {
                status.current_color = Color.FromArgb(255, (byte)(rnd.Next(0, 1000) % 256), (byte)(rnd.Next(0, 1000) % 256), (byte)(rnd.Next(0, 1000) % 256));
            }
            while (CheckColors() >= 50);
            SecretColor_Rectangle.Fill = new SolidColorBrush(status.secret_color);
            YourColor_Rectangle.Fill = new SolidColorBrush(status.current_color);
            Blue_Area.Text = "" + (int)status.current_color.B;
            Green_Area.Text = "" + (int)status.current_color.G;
            Red_Area.Text = "" + (int)status.current_color.R;
            Tests_Area.Text = Strings.Tests + ": " + status.tests;
            Timer_Area.Text = Strings.Time + ": " + status.timer;
            old_red = (int)status.current_color.R;
            old_green = (int)status.current_color.G;
            old_blue = (int)status.current_color.B;
            if (status.difficulty == GameDifficulty.Easy)
                status.helps = rnd.Next(1000) % 3;
            SetHelps();
            TestButton.Visibility = System.Windows.Visibility.Visible;
            Match_Area.Visibility = System.Windows.Visibility.Collapsed;

            Match_B_Area.Visibility = System.Windows.Visibility.Collapsed;
            Match_R_Area.Visibility = System.Windows.Visibility.Collapsed;
            Match_G_Area.Visibility = System.Windows.Visibility.Collapsed;

        }
        private double CheckColors()
        {
            var v1 = CheckColor(SetType.Red);
            var v2 = CheckColor(SetType.Green);
            var v3 = CheckColor(SetType.Blue);
            return Math.Round((v1 + v2 + v3) / 3, 2);
        }
        private double CheckColor(SetType type)
        {
            switch (type)
            {
                case SetType.Blue:

                    int val = Math.Abs((int)status.secret_color.B - (int)status.current_color.B);
                    return 100 - Math.Round((double)(100 * val / 255), 2);
                case SetType.Red:
                    val = Math.Abs((int)status.secret_color.R - (int)status.current_color.R);
                    return 100 - Math.Round((double)(100 * val / 255), 2);

                case SetType.Green:
                    val = Math.Abs((int)status.secret_color.G - (int)status.current_color.G);
                    return 100 - Math.Round((double)(100 * val / 255), 2);
                default:
                    return 0;
            }
        }
        private void RedButton_Click(object sender, RoutedEventArgs e)
        {
            status.enableTimer = true;
            current_type = SetType.Red;
            Slider.Value = (int)status.current_color.R;
            EnableSlider();
        }

        private void GreenButton_Click(object sender, RoutedEventArgs e)
        {
            status.enableTimer = true;
            current_type = SetType.Green;
            Slider.Value = (int)status.current_color.G;
            EnableSlider();
        }

        private void BlueButton_Click(object sender, RoutedEventArgs e)
        {
            status.enableTimer = true;
            current_type = SetType.Blue;
            Slider.Value = (int)status.current_color.B;
            EnableSlider();
        }

        private int GetTextBoxValue(TextBox box, int old_val)
        {
            try
            {
                int newVal = Int16.Parse(box.Text);
                newVal = Math.Min(newVal, 255);
                newVal = Math.Max(newVal, 0);
                return newVal;
            }
            catch (Exception ex)
            {
                ex.ToString();
                return old_val;
            }
        }
        int old_red = 0;
        int old_green = 0;
        int old_blue = 0;
        //private void Red_Area_KeyDown(object sender, KeyEventArgs e)
        //{
        //    if (e.Key == Key.Enter)
        //    {
        //        DisableSlider();
        //    }
        //    if (Red_Area.Text != "")
        //    {
        //        old_red = GetTextBoxValue(Red_Area, old_red);
        //        Red_Area.Text = "" + old_red;
        //    }
        //}

        //private void Green_Area_KeyDown(object sender, KeyEventArgs e)
        //{
        //    if (e.Key == Key.Enter)
        //    {
        //        DisableSlider();
        //    }
        //    if (Green_Area.Text != "")
        //    {
        //        old_green = GetTextBoxValue(Green_Area, old_green);
        //        Green_Area.Text = "" + old_green;
        //    }
        //}

        //private void Blue_Area_KeyDown(object sender, KeyEventArgs e)
        //{
        //    if (e.Key == Key.Enter)
        //    {
        //        DisableSlider();
        //    }
        //    if (Blue_Area.Text != "")
        //    {
        //        old_blue = GetTextBoxValue(Blue_Area, old_blue);
        //        Blue_Area.Text = "" + old_blue;
        //    }
        //}

        private void TestButton_Click(object sender, RoutedEventArgs e)
        {
            status.enableTimer = true;
            DisableSlider();
            var val = CheckColors();
            TestButton.Visibility = System.Windows.Visibility.Collapsed;
            Match_Area.Visibility = System.Windows.Visibility.Visible;
            Match_Area.Text = "" + val + " %";
            if (difficulty != GameDifficulty.Hard)
            {
                Match_B_Area.Text = "" + CheckColor(SetType.Blue) + " %";
                Match_R_Area.Text = "" + CheckColor(SetType.Red) + " %";
                Match_G_Area.Text = "" + CheckColor(SetType.Green) + " %";

                Match_B_Area.Visibility = System.Windows.Visibility.Visible;
                Match_R_Area.Visibility = System.Windows.Visibility.Visible;
                Match_G_Area.Visibility = System.Windows.Visibility.Visible;
            }
            status.tests++;
            Tests_Area.Text = Strings.Tests + ": " + status.tests;
            if (val == 100)
            {
                game_finished = true;
                PhoneApplicationService.Current.State.Remove("RGBFinder_status");
                PhoneApplicationService.Current.State.Add("RGBFinder_status", status);
                NavigationService.Navigate(new Uri("/ScorePage.xaml", UriKind.Relative));
            }
        }

        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            status.enableTimer = true;
            SetColor(current_type, (int)Slider.Value);
            //if (status.difficulty == GameDifficulty.Easy)
            //{
            //    Match_B_Area.Text = "" + CheckColor(SetType.Blue) + " %";
            //    Match_R_Area.Text = "" + CheckColor(SetType.Red) + " %";
            //    Match_G_Area.Text = "" + CheckColor(SetType.Green) + " %";
            //}
        }

        private void SetColor(SetType type, int value)
        {
            status.enableTimer = true;
            switch (type)
            {
                case SetType.Blue:
                    Blue_Area.Text = "" + value;
                    status.current_color.B = (byte)value;
                    break;
                case SetType.Red:
                    Red_Area.Text = "" + value;
                    status.current_color.R = (byte)value;
                    break;
                case SetType.Green:
                    Green_Area.Text = "" + value;
                    status.current_color.G = (byte)value;
                    break;
                default:
                    return;
            }
            YourColor_Rectangle.Fill = new SolidColorBrush(status.current_color);
        }
        public void EnableSlider()
        {
            Slider.IsEnabled = true;
            TestButton.Visibility = System.Windows.Visibility.Visible;
            Match_Area.Visibility = System.Windows.Visibility.Collapsed;
            if (status.difficulty != GameDifficulty.Easy)
            {
                Match_B_Area.Visibility = System.Windows.Visibility.Collapsed;
                Match_R_Area.Visibility = System.Windows.Visibility.Collapsed;
                Match_G_Area.Visibility = System.Windows.Visibility.Collapsed;
            }
            //PivotControl.IsHitTestVisible = false;
        }
        public void DisableSlider()
        {
            Slider.IsEnabled = false;
            //PivotControl.IsHitTestVisible = true;

        }

        private void Slider_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {

        }

        private void Red_Area_GotFocus(object sender, RoutedEventArgs e)
        {
            current_type = SetType.Red;
            EnableSlider();
        }

        private void Green_Area_GotFocus(object sender, RoutedEventArgs e)
        {
            current_type = SetType.Green;
            EnableSlider();
        }

        private void Blue_Area_GotFocus(object sender, RoutedEventArgs e)
        {
            current_type = SetType.Blue;
            EnableSlider();
        }

        private void Blue_Area_LostFocus(object sender, RoutedEventArgs e)
        {
            if (Blue_Area.Text == "")
            {
                Blue_Area.Text = "0";
                old_blue = GetTextBoxValue(Blue_Area, old_blue);
            }
            SetColor(SetType.Blue, GetTextBoxValue(Blue_Area, old_blue));
        }

        private void Green_Area_LostFocus(object sender, RoutedEventArgs e)
        {
            if (Green_Area.Text == "")
            {
                Green_Area.Text = "0";
                old_green = GetTextBoxValue(Green_Area, old_green);
            }
            SetColor(SetType.Green, GetTextBoxValue(Green_Area, old_green));
        }

        private void Red_Area_LostFocus(object sender, RoutedEventArgs e)
        {
            if (Red_Area.Text == "")
            {
                Red_Area.Text = "0";
                old_red = GetTextBoxValue(Red_Area, old_red);
            }
            SetColor(SetType.Red, GetTextBoxValue(Red_Area, old_red));

        }


        #region ACTIVATE_DEACTIVATE

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            PhoneApplicationService.Current.State.Remove("RGBFinder_status");
            if (status != null)
                PhoneApplicationService.Current.State.Add("RGBFinder_status", status);
            if (timer != null)
                timer.Dispose();
        }
        public static bool game_finished = false;
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (game_finished)
            {
                status = null;
                game_finished = false;
                NavigationService.GoBack();
            }

            try
            {
                if (PhoneApplicationService.Current.State.ContainsKey("RGBFinder_status"))
                {
                    status = (GameStatus)PhoneApplicationService.Current.State["RGBFinder_status"];
                    PhoneApplicationService.Current.State.Remove("RGBFinder_status");

                    //if (CheckColors() >= 100)
                    //{
                    //    status = null;
                    //    start_new_game = false;
                    //    NavigationService.GoBack();
                    //}

                    Timer_Area.Text = Strings.Timer + status.timer.ToString();
                    Tests_Area.Text = Strings.Tests + ": " + status.tests;
                    YourColor_Rectangle.Fill = new SolidColorBrush(status.current_color);
                    SecretColor_Rectangle.Fill = new SolidColorBrush(status.secret_color);

                    Blue_Area.Text = "" + (int)status.current_color.B;
                    Green_Area.Text = "" + (int)status.current_color.G;
                    Red_Area.Text = "" + (int)status.current_color.R;
                    old_red = (int)status.current_color.R;
                    old_green = (int)status.current_color.G;
                    old_blue = (int)status.current_color.B;

                    SetHelps();
                    if (timer != null)
                        timer.Dispose();
                    timer = new Timer(new TimerCallback(Timer_Callback), null, 0, 1000);
                }

                //else
                //    status = new GameStatus() ;

            }
            catch (Exception ex)
            {
                ex.ToString();
            }

        }
        #endregion

        private void SecretColor_Rectangle_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //status.current_color = status.secret_color;
        }

        private void SetHelps()
        {

            RedButton.IsEnabled = true;
            Red_Area.IsEnabled = true;
            GreenButton.IsEnabled = true;
            Green_Area.IsEnabled = true;
            BlueButton.IsEnabled = true;
            Blue_Area.IsEnabled = true;

            if (status.difficulty == GameDifficulty.Easy)
            {
                if (status.helps == 0)
                {
                    status.current_color.R = status.secret_color.R;
                    Red_Area.Text = "" + (int)status.current_color.R;
                    RedButton.IsEnabled = false;
                    Red_Area.IsEnabled = false;
                }
                else if (status.helps == 1)
                {
                    status.current_color.G = status.secret_color.G;
                    Green_Area.Text = "" + (int)status.current_color.G;
                    GreenButton.IsEnabled = false;
                    Green_Area.IsEnabled = false;
                }
                else if (status.helps == 2)
                {
                    status.current_color.B = status.secret_color.B;
                    Blue_Area.Text = "" + (int)status.current_color.B;
                    BlueButton.IsEnabled = false;
                    Blue_Area.IsEnabled = false;
                }
            }
        }

        private void Red_Area_KeyUp(object sender, KeyEventArgs e)
        {
            if (Red_Area.Text != "")
            {
                old_red = GetTextBoxValue(Red_Area, old_red);
                Red_Area.Text = "" + old_red;
            }
            Red_Area.SelectionStart = Red_Area.Text.Length;
        }

        private void Green_Area_KeyUp(object sender, KeyEventArgs e)
        {
            if (Green_Area.Text != "")
            {
                old_green = GetTextBoxValue(Green_Area, old_green);
                Green_Area.Text = "" + old_green;
            }
            Green_Area.SelectionStart = Green_Area.Text.Length;
        }

        private void Blue_Area_KeyUp(object sender, KeyEventArgs e)
        {
            if (Blue_Area.Text != "")
            {
                old_blue = GetTextBoxValue(Blue_Area, old_blue);
                Blue_Area.Text = "" + old_blue;
            }
            Blue_Area.SelectionStart = Blue_Area.Text.Length;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (start_new_game)
            {
                NewGame();
                start_new_game = false;
            }
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //if (isOverlayShowing == false)
            //{
            if (ads_open == false)
            {
                if (MessageBox.Show(Strings.AreYouSureToExit, "", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                    e.Cancel = true;
            }
            else
                ads_open = false;
        }

        //private void AdControl_AdControlError(object sender, Microsoft.Advertising.Mobile.UI.ErrorEventArgs e)
        //{
        //    Dispatcher.BeginInvoke(() =>
        //    {
        //        mmAdView.Visibility = System.Windows.Visibility.Visible;
        //        AdControl.Visibility = System.Windows.Visibility.Collapsed;
        //        AdControl.IsEnabled = false;
        //        mmAdView.IsEnabled = true;
        //        mmAdView.CallForAd();
        //    });
        //    return;
        //}

        //private void mmAdView_MMAdFailure(object sender, EventArgs e)
        //{
        //    Dispatcher.BeginInvoke(() =>
        //    {
        //        mmAdView.Visibility = System.Windows.Visibility.Collapsed;
        //        AdControl.Visibility = System.Windows.Visibility.Visible;
        //        //AdControl.RequestNextAd();
        //        AdControl.IsEnabled = true;
        //        mmAdView.IsEnabled = false;
        //    });
        //    return;
        //}

        //bool isOverlayShowing = false;
        //private void mmAdView_MMOverlayOpened(object sender, EventArgs e)
        //{
        //    isOverlayShowing = true;
        //}

        //private void mmAdView_MMOverlayClosed(object sender, EventArgs e)
        //{
        //    isOverlayShowing = false;
        //}
        bool ads_open = false;
        private void AdControl_AdEngaged(object sender, EventArgs e)
        {
            ads_open = true;
        }

        private void AdControl_AdDisengaged(object sender, EventArgs e)
        {
            ads_open = false;
        }


    }
}